package www.wxwnb.clerk.utils;

import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;

/**
 * Created by dingguanxu on 2017/8/17.
 */

public class BitmapUtil {

    public static Bitmap decodeSampleBitmapFromResource(Resources res, int resId, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(res, resId, options);

        options.inSampleSize = BitmapUtil.calculateSampleSize(options, reqWidth, reqHeight);

        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeResource(res, resId, options);
    }

    public static Bitmap decodeSampleBitmapFromPath(String pathName, int reqWidth, int reqHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();

        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(pathName, options);

        options.inSampleSize = BitmapUtil.calculateSampleSize(options, reqWidth, reqHeight);

        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(pathName, options);
    }

    private static int calculateSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        int width = options.outWidth;
        int hight = options.outHeight;
        int inSampleSize = 1;
        if (width >= reqWidth || hight >= reqHeight) {
            int halfWidth = width / 2;
            int halfHeith = hight / 2;
            while ((halfWidth / inSampleSize) >= reqWidth && (halfHeith / inSampleSize) >= reqHeight) {
                inSampleSize = inSampleSize * 2;
            }
        }
        return inSampleSize;
    }

}
